<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    

    <title>ArrayList的实现原理 | 程序员Sherwin</title>
    <meta name="author" content="Sherwin Wei">
    
    <meta name="description" content="1. ArrayList概述：&amp;emsp;&amp;emsp; ArrayList是List接口的可变数组的实现。实现了所有可选列表操作，并允许包括 null 在内的所有元素。除了实现 List 接口外，此类还提供一些方法来操作内部用来存储列表的数组的大小。
&amp;emsp;&amp;emsp; 每个ArrayList">
    

   
   <meta name="keywords" content="魏远标,Sherwin,java程序员,程序员Sherwin,程序员魏远标">
   
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta property="og:title" content="ArrayList的实现原理"/>
    <meta property="og:site_name" content="程序员Sherwin"/>

    
    <meta property="og:image" content=""/>
    

    <link rel="icon" type="image/png" href="/favicon.png">
    <link rel="alternate" href="/atom.xml" title="程序员Sherwin" type="application/atom+xml">
    <link rel="stylesheet" href="/css/lib/materialize.min.css">
    <link rel="stylesheet" href="/css/lib/font-awesome.min.css">
    <link rel="stylesheet" href="/css/style.css" media="screen" type="text/css">

    
        <link rel="stylesheet" href="/css/lib/prettify-tomorrow-night-eighties.css" type="text/css">
    
    <!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>


<body>
    <img src="/weixin_favicon.png" style="position: absolute; left: -9999px; opacity: 0; filter: alpha(opacity=0);">

    <nav class="indigo">
    <div class="nav-wrapper">
        <a href="#" data-activates="main-menu" class="button-collapse">
            <i class="fa fa-navicon"></i>
        </a>
        <div class="">
            <a href="/" class="brand-logo hide-on-med-and-down">程序员Sherwin</a>
            <ul class="right hide-on-med-and-down">
                
                    <li>
                        <a class="menu-home " href="/" >
                            <i class="fa fa-home "></i>
                            
                            首页
                        </a>
                    </li>
                
                    <li>
                        <a class="menu-archive " href="/archives" >
                            <i class="fa fa-archive "></i>
                            
                            归档
                        </a>
                    </li>
                
                    <li>
                        <a class="menu-category category-menu" href="javascript:;" data-activates="category-menu" >
                            <i class="fa fa-bookmark "></i>
                            
                            分类
                        </a>
                    </li>
                
                    <li>
                        <a class="menu-reading " href="/reading" >
                            <i class="fa fa-book "></i>
                            
                            读书
                        </a>
                    </li>
                
                    <li>
                        <a class="menu-about " href="/about" >
                            <i class="fa fa-user "></i>
                            
                            关于
                        </a>
                    </li>
                
                    <li>
                        <a class="menu-search modal-trigger " href="#search" >
                            <i class="fa fa-search "></i>
                            
                            搜索
                        </a>
                    </li>
                
            </ul>
            <div>
    <ul class="side-nav indigo darken-1" id="main-menu">
        
        <li class="side-user">
            <div class="row">
                <div class="col s4 no-padding">
                    <img class="avatar-image circle responsive-img" src="http://p5zbw6dku.bkt.clouddn.com/18-3-27/79800938.jpg" alt="User Avatar">
                </div>
                <div class="info col s8 valign-wrapper no-padding">
                    <div class="valign">
                        <p class="name">魏远标</p>
                        <p class="desc">Java后端/全栈</p>
                    </div>
                </div>
            </div>
        </li>
        

        
            <li class="no-padding">
                <a class="waves-effect menu-home " href="/" >
                    <i class="fa fa-home "></i>
                    
                    首页
                </a>
            </li>
        
            <li class="no-padding">
                <a class="waves-effect menu-archive " href="/archives" >
                    <i class="fa fa-archive "></i>
                    
                    归档
                </a>
            </li>
        
            <li class="no-padding">
                <a class="waves-effect menu-category category-menu" href="javascript:;" data-activates="category-menu" >
                    <i class="fa fa-bookmark "></i>
                    
                    分类
                </a>
            </li>
        
            <li class="no-padding">
                <a class="waves-effect menu-reading " href="/reading" >
                    <i class="fa fa-book "></i>
                    
                    读书
                </a>
            </li>
        
            <li class="no-padding">
                <a class="waves-effect menu-about " href="/about" >
                    <i class="fa fa-user "></i>
                    
                    关于
                </a>
            </li>
        
            <li class="no-padding">
                <a class="waves-effect menu-search modal-trigger " href="#search" >
                    <i class="fa fa-search "></i>
                    
                    搜索
                </a>
            </li>
        
    </ul>

    <ul class="side-nav indigo darken-1" id="category-menu">
    

            

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/java/">
                    java <span class="right">12 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/linux/">
                    linux <span class="right">2 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/web前端/">
                    web前端 <span class="right">1 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/生活/">
                    生活 <span class="right">7 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/网络/">
                    网络 <span class="right">1 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/java面试/">
                    java面试 <span class="right">3 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/juc/">
                    juc <span class="right">1 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/jvm/">
                    jvm <span class="right">2 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/mybatis/">
                    mybatis <span class="right">1 篇</span></a>
                </a>
            </li>

        

            <li class="collapse-level-0" collapse-level="0">
                <a class="no-padding" href="/categories/spring/">
                    spring <span class="right">1 篇</span></a>
                </a>
            </li>

        

    </ul>
</div>

        </div>
    </div>
</nav>

<div id="search" class="modal search-modal">
    <div class="row">
        <div class="input-field col s12">
              <input id="search-input" type="text">
              <label for="search-input">搜索</label>
        </div>

    </div>
    <div id="search-result" class="search-result col s12">

    </div>
</div>


    <main>
        <div class="container main-container">
    <nav class="page-nav hide-on-small-only">
    <div class="nav-wrapper indigo">
        <span class="breadcrumb">当前位置（分类目录）</span>
        
            
    
    
    <a class="breadcrumb" href="/categories/java/">java</a>


        

        
    </div>
</nav>

<article>
    <div class="card">
        <div class="card-content">
            

            <div class="article-title">
                
    
        <h1>ArrayList的实现原理</h1>
    


            </div>
            <time class="pink-link-context" datetime="2018-06-01T01:03:02.000Z"><a href="/java/1.ArrayList的实现原理/">2018-06-01</a></time>

            <span id="busuanzi_container_page_pv" class="read-times-container">
    <i class="fa fa-eye"></i>
    <span id="busuanzi_value_page_pv"></span>
</span>

            
    <div class="tags-row">
        
            <a href="/tags/java基础/" class="chip pink lighten-1">java基础</a>
        
    </div>


            <div class="toc pink-link-context hide-on-med-and-down">
    <ol class="section table-of-contents"><li class="section table-of-contents-item section table-of-contents-level-3"><a class="section table-of-contents-link" href="#1-ArrayList概述："><span class="section table-of-contents-text">1. ArrayList概述：</span></a></li><li class="section table-of-contents-item section table-of-contents-level-3"><a class="section table-of-contents-link" href="#2-ArrayList的实现："><span class="section table-of-contents-text">2. ArrayList的实现：</span></a><ol class="section table-of-contents-child"><li class="section table-of-contents-item section table-of-contents-level-4"><a class="section table-of-contents-link" href="#1-底层使用数组实现："><span class="section table-of-contents-text">1) 底层使用数组实现：</span></a></li><li class="section table-of-contents-item section table-of-contents-level-4"><a class="section table-of-contents-link" href="#2-构造方法："><span class="section table-of-contents-text">2) 构造方法：</span></a></li><li class="section table-of-contents-item section table-of-contents-level-4"><a class="section table-of-contents-link" href="#3-存储："><span class="section table-of-contents-text">3) 存储：</span></a></li><li class="section table-of-contents-item section table-of-contents-level-4"><a class="section table-of-contents-link" href="#4-读取："><span class="section table-of-contents-text">4) 读取：</span></a></li><li class="section table-of-contents-item section table-of-contents-level-4"><a class="section table-of-contents-link" href="#5-删除："><span class="section table-of-contents-text">5) 删除：</span></a></li><li class="section table-of-contents-item section table-of-contents-level-4"><a class="section table-of-contents-link" href="#6-调整数组容量："><span class="section table-of-contents-text">6) 调整数组容量：</span></a></li><li class="section table-of-contents-item section table-of-contents-level-4"><a class="section table-of-contents-link" href="#7-Fail-Fast机制："><span class="section table-of-contents-text">7) Fail-Fast机制：</span></a></li></ol></li></ol>
</div>


            <div class="entry pink-link-context">
                <h3 id="1-ArrayList概述："><a href="#1-ArrayList概述：" class="headerlink" title="1. ArrayList概述："></a>1. ArrayList概述：</h3><p>&emsp;&emsp; ArrayList是List接口的可变数组的实现。实现了所有可选列表操作，并允许包括 null 在内的所有元素。除了实现 List 接口外，此类还提供一些方法来操作内部用来存储列表的数组的大小。</p>
<p>&emsp;&emsp; 每个ArrayList实例都有一个容量，该容量是指用来存储列表元素的数组的大小。它总是至少等于列表的大小。随着向ArrayList中不断添加元素，其容量也自动增长。自动增长会带来数据向新数组的重新拷贝，因此，如果可预知数据量的多少，可在构造ArrayList时指定其容量。在添加大量元素前，应用程序也可以使用ensureCapacity操作来增加ArrayList实例的容量，这可以减少递增式再分配的数量。 </p>
<ul>
<li>注意，此实现不是同步的。如果多个线程同时访问一个ArrayList实例，而其中至少一个线程从结构上修改了列表，那么它必须保持外部同步。</li>
</ul>
<h3 id="2-ArrayList的实现："><a href="#2-ArrayList的实现：" class="headerlink" title="2. ArrayList的实现："></a>2. ArrayList的实现：</h3><p>&emsp;&emsp; 对于ArrayList而言，它实现List接口、底层使用数组保存所有元素。其操作基本上是对数组的操作。下面我们来分析ArrayList的源代码：</p>
<h4 id="1-底层使用数组实现："><a href="#1-底层使用数组实现：" class="headerlink" title="1) 底层使用数组实现："></a>1) 底层使用数组实现：</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">private transient Object[] elementData;</span><br></pre></td></tr></table></figure>
<h4 id="2-构造方法："><a href="#2-构造方法：" class="headerlink" title="2) 构造方法："></a>2) 构造方法：</h4><p> &emsp;&emsp;  ArrayList提供了三种方式的构造器，可以构造一个默认初始容量为10的空列表、构造一个指定初始容量的空列表以及构造一个包含指定collection的元素的列表，这些元素按照该collection的迭代器返回它们的顺序排列的。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public ArrayList() &#123;  </span><br><span class="line">    this(10);  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">public ArrayList(int initialCapacity) &#123;  </span><br><span class="line">    super();  </span><br><span class="line">    if (initialCapacity &lt; 0)  </span><br><span class="line">        throw new IllegalArgumentException(&quot;Illegal Capacity: &quot;+ initialCapacity);  </span><br><span class="line">    this.elementData = new Object[initialCapacity];  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">public ArrayList(Collection&lt;? extends E&gt; c) &#123;  </span><br><span class="line">    elementData = c.toArray();  </span><br><span class="line">    size = elementData.length;  </span><br><span class="line">    // c.toArray might (incorrectly) not return Object[] (see 6260652)  </span><br><span class="line">    if (elementData.getClass() != Object[].class)  </span><br><span class="line">        elementData = Arrays.copyOf(elementData, size, Object[].class);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="3-存储："><a href="#3-存储：" class="headerlink" title="3) 存储："></a>3) 存储：</h4><p>&emsp;&emsp; ArrayList提供了set(int index, E element)、add(E e)、add(int index, E element)、addAll(Collection&lt;? extends E&gt; c)、addAll(int index, Collection&lt;? extends E&gt; c)这些添加元素的方法。下面我们一一讲解：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">// 用指定的元素替代此列表中指定位置上的元素，并返回以前位于该位置上的元素。  </span><br><span class="line">public E set(int index, E element) &#123;  </span><br><span class="line">    RangeCheck(index);  </span><br><span class="line">  </span><br><span class="line">    E oldValue = (E) elementData[index];  </span><br><span class="line">    elementData[index] = element;  </span><br><span class="line">    return oldValue;  </span><br><span class="line">&#125;  </span><br><span class="line"></span><br><span class="line">// 将指定的元素添加到此列表的尾部。  </span><br><span class="line">public boolean add(E e) &#123;  </span><br><span class="line">    ensureCapacity(size + 1);   </span><br><span class="line">    elementData[size++] = e;  </span><br><span class="line">    return true;  </span><br><span class="line">&#125;  </span><br><span class="line"></span><br><span class="line">// 将指定的元素插入此列表中的指定位置。  </span><br><span class="line">// 如果当前位置有元素，则向右移动当前位于该位置的元素以及所有后续元素（将其索引加1）。  </span><br><span class="line">public void add(int index, E element) &#123;  </span><br><span class="line">    if (index &gt; size || index &lt; 0)  </span><br><span class="line">        throw new IndexOutOfBoundsException(&quot;Index: &quot;+index+&quot;, Size: &quot;+size);  </span><br><span class="line">    // 如果数组长度不足，将进行扩容。  </span><br><span class="line">    ensureCapacity(size+1);  // Increments modCount!!  </span><br><span class="line">    // 将 elementData中从Index位置开始、长度为size-index的元素，  </span><br><span class="line">    // 拷贝到从下标为index+1位置开始的新的elementData数组中。  </span><br><span class="line">    // 即将当前位于该位置的元素以及所有后续元素右移一个位置。  </span><br><span class="line">    System.arraycopy(elementData, index, elementData, index + 1, size - index);  </span><br><span class="line">    elementData[index] = element;  </span><br><span class="line">    size++;  </span><br><span class="line">&#125;  </span><br><span class="line"></span><br><span class="line">// 按照指定collection的迭代器所返回的元素顺序，将该collection中的所有元素添加到此列表的尾部。  </span><br><span class="line">public boolean addAll(Collection&lt;? extends E&gt; c) &#123;  </span><br><span class="line">    Object[] a = c.toArray();  </span><br><span class="line">    int numNew = a.length;  </span><br><span class="line">    ensureCapacity(size + numNew);  // Increments modCount  </span><br><span class="line">    System.arraycopy(a, 0, elementData, size, numNew);  </span><br><span class="line">    size += numNew;  </span><br><span class="line">    return numNew != 0;  </span><br><span class="line">&#125;  </span><br><span class="line">// 从指定的位置开始，将指定collection中的所有元素插入到此列表中。  </span><br><span class="line">public boolean addAll(int index, Collection&lt;? extends E&gt; c) &#123;  </span><br><span class="line">    if (index &gt; size || index &lt; 0)  </span><br><span class="line">        throw new IndexOutOfBoundsException(  </span><br><span class="line">            &quot;Index: &quot; + index + &quot;, Size: &quot; + size);  </span><br><span class="line">  </span><br><span class="line">    Object[] a = c.toArray();  </span><br><span class="line">    int numNew = a.length;  </span><br><span class="line">    ensureCapacity(size + numNew);  // Increments modCount  </span><br><span class="line">  </span><br><span class="line">    int numMoved = size - index;  </span><br><span class="line">    if (numMoved &gt; 0)  </span><br><span class="line">        System.arraycopy(elementData, index, elementData, index + numNew, numMoved);  </span><br><span class="line">  </span><br><span class="line">    System.arraycopy(a, 0, elementData, index, numNew);  </span><br><span class="line">    size += numNew;  </span><br><span class="line">    return numNew != 0;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="4-读取："><a href="#4-读取：" class="headerlink" title="4) 读取："></a>4) 读取：</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">// 返回此列表中指定位置上的元素。  </span><br><span class="line">public E get(int index) &#123;  </span><br><span class="line">    RangeCheck(index);  </span><br><span class="line">  </span><br><span class="line">    return (E) elementData[index];  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="5-删除："><a href="#5-删除：" class="headerlink" title="5) 删除："></a>5) 删除：</h4><p>   ArrayList提供了根据下标或者指定对象两种方式的删除功能。如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">// 移除此列表中指定位置上的元素。  </span><br><span class="line">public E remove(int index) &#123;  </span><br><span class="line">    RangeCheck(index);  </span><br><span class="line">  </span><br><span class="line">    modCount++;  </span><br><span class="line">    E oldValue = (E) elementData[index];  </span><br><span class="line">  </span><br><span class="line">    int numMoved = size - index - 1;  </span><br><span class="line">    if (numMoved &gt; 0)  </span><br><span class="line">        System.arraycopy(elementData, index+1, elementData, index, numMoved);  </span><br><span class="line">    elementData[--size] = null; // Let gc do its work  </span><br><span class="line">  </span><br><span class="line">    return oldValue;  </span><br><span class="line">&#125;  </span><br><span class="line">// 移除此列表中首次出现的指定元素（如果存在）。这是应为ArrayList中允许存放重复的元素。  </span><br><span class="line">public boolean remove(Object o) &#123;  </span><br><span class="line">    // 由于ArrayList中允许存放null，因此下面通过两种情况来分别处理。  </span><br><span class="line">    if (o == null) &#123;  </span><br><span class="line">        for (int index = 0; index &lt; size; index++)  </span><br><span class="line">            if (elementData[index] == null) &#123;  </span><br><span class="line">                // 类似remove(int index)，移除列表中指定位置上的元素。  </span><br><span class="line">                fastRemove(index);  </span><br><span class="line">                return true;  </span><br><span class="line">            &#125;  </span><br><span class="line">&#125; else &#123;  </span><br><span class="line">    for (int index = 0; index &lt; size; index++)  </span><br><span class="line">        if (o.equals(elementData[index])) &#123;  </span><br><span class="line">            fastRemove(index);  </span><br><span class="line">            return true;  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">    return false;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>注意：从数组中移除元素的操作，也会导致被移除的元素以后的所有元素的向左移动一个位置。<h4 id="6-调整数组容量："><a href="#6-调整数组容量：" class="headerlink" title="6) 调整数组容量："></a>6) 调整数组容量：</h4>&emsp;&emsp; 从上面介绍的向ArrayList中存储元素的代码中，我们看到，每当向数组中添加元素时，都要去检查添加后元素的个数是否会超出当前数组的长度，如果超出，数组将会进行扩容，以满足添加数据的需求。数组扩容通过一个公开的方法ensureCapacity(int minCapacity)来实现。在实际添加大量元素前，我也可以使用ensureCapacity来手动增加ArrayList实例的容量，以减少递增式再分配的数量。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public void ensureCapacity(int minCapacity) &#123;  </span><br><span class="line">    modCount++;  </span><br><span class="line">    int oldCapacity = elementData.length;  </span><br><span class="line">    if (minCapacity &gt; oldCapacity) &#123;  </span><br><span class="line">        Object oldData[] = elementData;  </span><br><span class="line">        int newCapacity = (oldCapacity * 3)/2 + 1;  </span><br><span class="line">            if (newCapacity &lt; minCapacity)  </span><br><span class="line">                newCapacity = minCapacity;  </span><br><span class="line">      // minCapacity is usually close to size, so this is a win:  </span><br><span class="line">      elementData = Arrays.copyOf(elementData, newCapacity);  //对于数组里面的元素是复杂Object的时候是浅拷贝</span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>&emsp;&emsp;从上述代码中可以看出，数组进行扩容时，会将老数组中的元素重新拷贝一份到新的数组中，每次数组容量的增长大约是其原容量的1.5倍。这种操作的代价是很高的，因此在实际使用时，我们应该尽量避免数组容量的扩张。当我们可预知要保存的元素的多少时，要在构造ArrayList实例时，就指定其容量，以避免数组扩容的发生。或者根据实际需求，通过调用ensureCapacity方法来手动增加ArrayList实例的容量。<br>&emsp;&emsp; ArrayList还给我们提供了将底层数组的容量调整为当前列表保存的实际元素的大小的功能。它可以通过trimToSize方法来实现。代码如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public void trimToSize() &#123;  </span><br><span class="line">    modCount++;  </span><br><span class="line">    int oldCapacity = elementData.length;  </span><br><span class="line">    if (size &lt; oldCapacity) &#123;  </span><br><span class="line">        elementData = Arrays.copyOf(elementData, size);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="7-Fail-Fast机制："><a href="#7-Fail-Fast机制：" class="headerlink" title="7) Fail-Fast机制："></a>7) Fail-Fast机制：</h4><p>&emsp;&emsp;ArrayList也采用了快速失败的机制，通过记录modCount参数来实现。在面对并发的修改时，迭代器很快就会完全失败，而不是冒着在将来某个不确定时间发生任意不确定行为的风险。</p>
<p>具体介绍请参考我之前的文章深入Java集合学习系列：HashMap的实现原理 中的Fail-Fast机制。</p>

                
<p class="pink-link-context">
    <a href="/java/2.HashMap的实现原理/" rel="next" title="HashMap的实现原理">
    上一篇：HashMap的实现原理
  </a>
</p>



<p class="pink-link-context">
    <a href="/java/jvm/JVM内存区域详解（Eden Space、Survivor Space、Old Gen、Code Cache和Perm Gen）/" rel="next" title="JVM内存区域详解（Eden Space、Survivor Space、Old Gen、Code Cache和Perm Gen）">
    下一篇：JVM内存区域详解（Eden Space、Survivor Space、Old Gen、Code Cache和Perm Gen）
  </a>
</p>


            </div>
			
        </div>
    </div>
</article>




    <section id="comments">
        <!--高速版，加载速度快，使用前需测试页面的兼容性-->
        <div id="SOHUCS" sid="ArrayList的实现原理"></div>
        <script>
          (function(){
            var appid = 'cytwu2Jh8',
            conf = 'prod_f36aa8fb3548cb02167fd6c482acf807';
            var doc = document,
            s = doc.createElement('script'),
            h = doc.getElementsByTagName('head')[0] || doc.head || doc.documentElement;
            s.type = 'text/javascript';
            s.charset = 'utf-8';
            s.src =  'http://assets.changyan.sohu.com/upload/changyan.js?conf='+ conf +'&appid=' + appid;
            h.insertBefore(s,h.firstChild);
            window.SCS_NO_IFRAME = true;
          })()
        </script>    
    </section>





</div>

        <div class="fixed-action-btn float-sitemap">
    <a class="btn-floating btn-large pink">
      <i class="fa fa-caret-square-o-up"></i>
    </a>
    <ul>
      <li><a class="btn-return-top btn-floating waves-effect green" title="回到顶部"><i class="fa fa-arrow-circle-o-up"></i></a></li>
      <li><a class="btn-floating waves-effect button-collapse yellow darken-1"  data-activates="main-menu" title="菜单"><i class="fa fa-navicon"></i></a></li>
    </ul>
  </div>

    </main>
    <footer class="page-footer indigo darken-1">
    
    <div class="footer-container container">
        <div class="row">
            
            <div class="social-group col m4 s12">
                <h5 class="white-text">社交</h5>
                
                    <a class="social-link" href="https://weibo.com/1903200010" target="_blank">
                        <i class="fa fa-2x fa-weibo"></i>
                    </a>
                
                    <a class="social-link" href="https://github.com/sherwin28" target="_blank">
                        <i class="fa fa-2x fa-github"></i>
                    </a>
                
                    <a class="social-link" href="/atom.xml" target="_blank">
                        <i class="fa fa-2x fa-rss"></i>
                    </a>
                
                
     <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <div class="site-visitors-container white-text">
        <span>
            <i class="fa fa-user"></i>
            <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
        </span>
        <span>&nbsp;|&nbsp;</span>
        <span>
            <i class="fa fa-eye"></i>
            <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
        </span>
    </div>


            </div>
            

            
            <div class="col m8 s12">
                <h5 class="white-text">友情链接</h5>
                
                    <a class="social-link" href="http://blog.didispace.com/" target="_blank">程序猿DD</a>
                
                    <a class="social-link" href="https://springcloud.cc/" target="_blank">Spring Cloud中文网</a>
                
                    <a class="social-link" href="http://itmuch.com/" target="_blank">周立|Spring Cloud </a>
                
            </div>
            
        </div>
    </div>
    

    <div class="footer-copyright pink-link-context">
        <div class="container">
            © 2018 weiyuanbiao.cn, All rights reserved.
            <a href="http://weiyuanbiao.cn" style="margin-left:10px;">weiyuanbiao.cn</a>
            <a href="http://www.miitbeian.gov.cn" target="_blank" style="margin-left:10px;">粤ICP备15018188号-1</a>
            <!-- 
            <p class="right" style="margin-top: 0;">本博客由 <a href="https://hexo.io">Hexo</a> 强力驱动 | 主题 <a href="https://github.com/raytaylorlin/hexo-theme-raytaylorism">raytaylorism</a></p>
            -->
        </div>
    </div>
</footer>


<noscript>
    <div class="noscript">
        <p class="center-align">当前网速较慢或者你使用的浏览器不支持博客特定功能，请尝试刷新或换用Chrome、Firefox等现代浏览器</p>
    </div>
</noscript>
<div class="noscript">
    <p class="center-align">当前网速较慢或者你使用的浏览器不支持博客特定功能，请尝试刷新或换用Chrome、Firefox等现代浏览器</p>
</div>


<script src="/js/jquery.min.js"></script>
<script src="/js/materialize.min.js"></script>

<script>
    (function($) {
        $(document).ready(function() {
            // 隐藏禁用javascript（针对微信内置浏览器）的提示
            $('.noscript').hide();

            // 图片缩放效果
            var $imgs = $('img').not('.slider-image').not('.avatar-image').not('.carousel-image').not('.card-cover-image').not('.qrcode');

            // 给图片加上点击放大效果（materialbox插件）
            $imgs.addClass('materialboxed').each(function(i, el) {
                $(this).attr('data-caption', $(this).attr('alt') || ' ');
            }).materialbox();

            // 优化表格的显示
            $('table').each(function() {
                var $table = $(this);
                // 除去多行代码的情况
                if ($table.find('pre').length == 0) {
                    $table.addClass('responsive-table striped bordered');
                }
            });

            // 首页幻灯片
            $('.slider').slider({indicators: true, full_width: true, interval: 8000});

            $(".button-collapse").sideNav();
            $(".category-menu").sideNav();

            // 针对gallery post
            $('.carousel').carousel({full_width: true});
            $('.carousel-control.prev').click(function() {
                $('.carousel').carousel('prev');
            });
            $('.carousel-control.next').click(function() {
                $('.carousel').carousel('next');
            });

            // 文章目录
            $('article').not('.simple-article').find('h1').add('h2').add('h3').add('h4').add('h5').add('h6').scrollSpy();

            // 目录随屏幕滚动（防止目录过长越过footer）
            var $toc = $('.toc');
            var scrollTargetTop = 0;
            $(window).scroll(function() {
                var $activeLink = $toc.find('a.active.section');
                if ($(window).scrollTop() < 100) {
                    scrollTargetTop = 0;
                } else {
                    if ($activeLink[0]) {
                        scrollTargetTop = $activeLink.offset().top - $toc.offset().top;
                    }
                }
                $toc.css('top', '-' + scrollTargetTop + 'px');
            });

            // 修正文章目录的left-border颜色
            var color = $('.table-of-contents-text').css('color');
            $('.table-of-contents-link').css('border-left-color', color);

            // 针对移动端做的优化：FAB按钮点击一下收回
            if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
                $('.fixed-action-btn').addClass('click-to-toggle');
            }
            // 回到顶部
            $('.btn-return-top').click(function() {
                $('body, html').animate({
                    scrollTop: 0
                }, 500);
            });

            // 重置读书页面的Tab标签页的颜色
            $('li.tab a').hover(function() {
                $(this).toggleClass('text-lighten-4');
            });
            $('.indicator').addClass('pink lighten-2');

            
            // 添加new标签
            $('.menu-reading').append('<span class="new badge pink"></span>');
            

            // 搜索功能
            $('.modal-trigger').leanModal({
                // 打开搜索框时自动聚焦
                ready: function() {
                    if ($('#search').is(":visible")) {
                        $('#search-input').focus();
                    }
                }
            });
            var searchXml = "search.xml";
            if (searchXml.length == 0) {
             	searchXml = "search.xml";
            }
            var searchPath = "/" + searchXml;
            initSearch(searchPath, 'search-input', 'search-result');
        });

        // 初始化搜索与匹配函数
        var initSearch = function(path, search_id, content_id) {
            'use strict';
            $.ajax({
                url: path,
                dataType: "xml",
                success: function(xmlResponse) {
                    // get the contents from search data
                    var datas = $("entry", xmlResponse).map(function() {
                        return {
                            title: $("title", this).text(),
                            content: $("content", this).text(),
                            url: $("url", this).text()
                        };
                    }).get();
                    var $input = document.getElementById(search_id);
                    var $resultContent = document.getElementById(content_id);
                    $input.addEventListener('input', function() {
                        var str = '<ul class=\"search-result-list\">';
                        var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                        $resultContent.innerHTML = "";
                        if (this.value.trim().length <= 0) {
                            return;
                        }
                        // perform local searching
                        datas.forEach(function(data) {
                            var isMatch = true;
                            var content_index = [];
                            var data_title = data.title.trim().toLowerCase();
                            var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                            var data_url = data.url;
                            var index_title = -1;
                            var index_content = -1;
                            var first_occur = -1;
                            // only match artiles with not empty titles and contents
                            if (data_title != '' && data_content != '') {
                                keywords.forEach(function(keyword, i) {
                                    index_title = data_title.indexOf(keyword);
                                    index_content = data_content.indexOf(keyword);
                                    if (index_title < 0 && index_content < 0) {
                                        isMatch = false;
                                    } else {
                                        if (index_content < 0) {
                                            index_content = 0;
                                        }
                                        if (i == 0) {
                                            first_occur = index_content;
                                        }
                                    }
                                });
                            }
                            // show search results
                            if (isMatch) {
                                keywords.forEach(function(keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    data_title = data_title.replace(regS, "<span class=\"search-keyword pink lighten-2\">" + keyword + "</span>");
                                });

                                str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                                var content = data.content.trim().replace(/<[^>]+>/g, "");
                                if (first_occur >= 0) {
                                    // cut out 100 characters
                                    var start = first_occur - 20;
                                    var end = first_occur + 80;
                                    if (start < 0) {
                                        start = 0;
                                    }
                                    if (start == 0) {
                                        end = 100;
                                    }
                                    if (end > content.length) {
                                        end = content.length;
                                    }
                                    var match_content = content.substring(start, end);
                                    // highlight all keywords
                                    keywords.forEach(function(keyword) {
                                        var regS = new RegExp(keyword, "gi");
                                        match_content = match_content.replace(regS, "<span class=\"search-keyword pink lighten-2\">" + keyword + "</span>");
                                    });

                                    str += "<p class=\"search-result\">..." + match_content + "...</p>"
                                }
                                str += "</li>";
                            }
                        });
                        str += "</ul>";
                        $resultContent.innerHTML = str;
                    });
                }
            });
        }
    })(jQuery);
</script>


<script src="/js/prettify.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("pre").addClass("prettyprint");
        prettyPrint();
    });
</script>




<script type="text/javascript" src="http://tajs.qq.com/stats?sId=65472120" charset="UTF-8"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
  tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});
</script>
<script type="text/javascript" async
  src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML">
</script>





</body>
</html>
